<?php
$loader->requireOnce('includes/EwhExport/EwhExportProc.class.php');
$loader->requireOnce('includes/EwhImport/EwhImportDrugMaterialProc.class.php');
$loader->requireOnce('includes/EwhExport/EwhReqExportQueueProc.class.php');
$loader->requireOnce('includes/PickDM/PickDMModelBuilder.class.php');

/**
 * Controler for valuate drug/material prices.
 * @package modules.dept_pharmacy.controllers
 * @author viethd
 * @version $Id$
 * @copyright 2009 LHV Company
 */
class C_EwhExportDrugMaterial extends Controller {
    private $logger ;
    private $phaExportPro;
    private $ewhReqExportQueueProc;
    private $ewhImportDrugMaterialProc;
    function __construct($template_mod = "general") {
        parent::Controller();
        $this->logger = LoggerManager::getLogger('module.dept_pharmacy.controllers.C_EwhExportDrugMaterial');
        $this->template_mod = $template_mod;
        $this->view->path="pha_ewh_export_drug_material";
        $this->phaExportPro = new EwhExportProc($this);
        $this->ewhReqExportQueueProc = new EwhReqExportQueueProc(null);
        $this->ewhImportDrugMaterialProc = new EwhImportDrugMaterialProc(null);

    }
    public function actionProcessExpRequest($reqExTicketId = 0) {
        if (isset($_GET['requestTicketId'])) {
            $reqExTicketId = $_GET['reqExTicketId'];
        }
        $filter = array(
        'enum_destination'=>EnumerationConstant::PHA_REQ_DESINATION_EWH);        
        $request = $this->ewhReqExportQueueProc->getRequest($reqExTicketId, $filter);
        $exTicket = $this->phaExportPro->getExTicketOfGivenReq($reqExTicketId);
        $arrReqExpTicketDetailInfo =  $this->phaExportPro->listReqExticketDetail($reqExTicketId);

        $html = '';
        $this->assignDefaultValue();
         
        $this->assign('reqExpTicketInfo', null);
        if ($request != null && !empty($request)) {
            $this->assign('reqExpTicketInfo', $request);
        }
        $this->assign('exTicketInfo', $exTicket);
        $this->assign('acceptedStatus', EnumerationConstant::PHA_REQ_STATUS_ACCEPTED_KEY);
                
        $this->assign('arrReqExpTicketDetailInfo', $arrReqExpTicketDetailInfo);

        $html = $this->view->render('process.html');
        return $html;
    }
    public function actionProcessExpRequestViewOnly($reqExTicketId = 0) {
        if (isset($_GET['requestTicketId'])) {
            $reqExTicketId = $_GET['reqExTicketId'];
        }
        $filter = array(
        'enum_destination'=>EnumerationConstant::PHA_REQ_DESINATION_EWH);        
        $request = $this->ewhReqExportQueueProc->getRequest($reqExTicketId, $filter);
        $exTicket = $this->phaExportPro->getExTicketOfGivenReq($reqExTicketId);
        $arrApprovedExpTicketDetailInfo =  $this->phaExportPro->listApprovedExticketDetail($reqExTicketId);

        $html = '';
        $this->assignDefaultValue();
         
        $this->assign('reqExpTicketInfo', null);
        if ($request != null && !empty($request)) {
            $this->assign('reqExpTicketInfo', $request);
        }
        $this->assign('exTicketInfo', $exTicket);
        $this->assign('acceptedStatus', EnumerationConstant::PHA_REQ_STATUS_ACCEPTED_KEY);
                
        $this->assign('arrReqExpTicketDetailInfo', $arrApprovedExpTicketDetailInfo);

        $html = $this->view->render('process_view_only.html');
        return $html;
    }
    public function actionPickDrugAjax() {
        $this->logger->info('Start actionPickDrugAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),
        'result'=>'');
        $divData = $_POST['divIdData'];
        $reqExticketDetailId = $_POST['reqExticketDetailId'];         
        $reqExticketDetailInfo = $this->phaExportPro->getReqExticketDetail($reqExticketDetailId);
        $dmList = $this->ewhImportDrugMaterialProc->listAllowSellDMOfGivenNameId($reqExticketDetailInfo['pha_drug_material_id']);
        $this->assign('divIdData',$divData);
        $this->assign('allowSellDMList', $dmList);
        $this->assign('reqExticketDetailInfo', $reqExticketDetailInfo);
        
        $result['result'] = $this->view->render('pick_drug_material.html');
         
        $this->logger->info('Finish actionPickDrugAjax');
        return json_encode($result);

    }
    private function assignDefaultValue() {

        
        $orders =   L10nHelper::getYMDorder();
        $this->assign('userFullName',  $this->_me->get_person_name());
        $this->assign('exportSourceName', '');
        $this->assign('datePart_0', $orders[0]);
        $this->assign('datePart_1', $orders[1]);
        $this->assign('datePart_2', $orders[2]);
         
    }
    public function actionAcceptReqExTicketAjax($reqExTicketId = 0) {
        $this->logger->info('Start actionCreateExportTicketAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),
        'result'=>array('code'=>'','id'=>''));

        if (isset($_POST['reqExTicketId'])) {
            $reqExTicketId = $_POST['reqExTicketId'];
        }

        if (isset($_POST['expTicketId'])) {
            $expTicketId = $_POST['expTicketId'];
        }
        $appDate = date('Y-m-d hh:ss');

        if (isset($_POST['appDate'])) {
            $appDate = $_POST['appDate'];
        }
        $appNote = '';
        if (isset($_POST['appNote'])) {
            $appNote = $_POST['appNote'];
        }       

        $data = array(
        'app_date'      =>  $appDate,
        'app_user_id'   =>  $this->_me->get_person_id(),        
        'pha_req_exticket_id' => $reqExTicketId, 
        'note' => $appNote
        );

        try
        {
            if ($expTicketId =='' || $expTicketId == 0) {
                $result['result'] = $this->phaExportPro->createAcceptedExportTicket($data);
            } else {
                //roll back before save new
                $this->phaExportPro->rollBackApprovedExticket($expTicketId);
                $result['result'] = $this->phaExportPro->saveAcceptedExportTicket($expTicketId, $data);
            }
            $this->acceptingDrugMaterial($reqExTicketId, $result['result']['id']);

        } catch (EwhExportException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = EwhErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('actionCreateExportTicketAjax fail. Error detail: '. $ex->getMessage());
        } catch (Exception $ex) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('actionCreateExportTicketAjax fail. Error detail: '. $ex->getMessage());

        }
         
        $this->logger->info('Finish actionCreateExportTicketAjax');
        return json_encode($result);
    }
    
    private function acceptingDrugMaterial($reqExTicketId, $phaEwhExticketId) {
        $arrReqExpTicketDetailInfo =  $this->phaExportPro->listReqExticketDetail($reqExTicketId);
        
        $pickBuilder = new PickDMModelBuilder($reqExTicketId);
        
        foreach ($arrReqExpTicketDetailInfo as $item) {            
            $reqDetailId = $item['pha_req_exticket_detail_id'];
            $data = array(            
            'pha_ewh_exticket_id' => $phaEwhExticketId,
            'pha_drug_material_id'=> $item['pha_drug_material_id'],
            'req_quantity' => $item['quantity'],
            'approve_quantity' => $_POST['totalApprovedNum' . $reqDetailId],
            'note' => $_POST['note' . $reqDetailId],
            'pha_req_exticket_detail_id' => $reqDetailId );
            $pickBuilder->addModelData($data);
            $approvedNum = $_POST['approvedNum' . $reqDetailId];
            $approvedRefId = $_POST['approvedRefId' . $reqDetailId];
            if (is_array($approvedNum)) {
                $count = count($approvedNum);
                for ($index = 0; $index < $count; $index++) {
                    $pickBuilder->addDetailPicking($reqDetailId, $approvedRefId[$index], $approvedNum[$index]);                	
                }                
            } 
        }    
        $pickBuilder->save();    
    }

    public function actionRejectReqExTicketAjax($reqExTicketId = 0) {
        $this->logger->info('Start actionCreateExportTicketAjax');
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''),
        'result'=>array('code'=>'','id'=>''));

        if (isset($_POST['reqExTicketId'])) {
            $reqExTicketId = $_POST['reqExTicketId'];
        }

        if (isset($_POST['expTicketId'])) {
            $expTicketId = $_POST['expTicketId'];
        }
        $appDate = date('Y-m-d hh:ss');

        if (isset($_POST['appDate'])) {
            $appDate = $_POST['appDate'];
        }
        $appNote = '';
        if (isset($_POST['appNote'])) {
            $appNote = $_POST['appNote'];
        }

       
        $data = array(
        'app_date'      =>  $appDate,
        'app_user_id'   =>  $this->_me->get_person_id(),        
        'pha_req_exticket_id' => $reqExTicketId, 
        'note' => $appNote
        );

        try
        {
            
                
            if ($expTicketId =='' || $expTicketId == 0) {
                $result['result'] = $this->phaExportPro->rejectExpTicket($data);
            } else {
                //roll back before save new
                $this->phaExportPro->rollBackApprovedExticket($expTicketId);                
                $result['result'] = $this->phaExportPro->saveRejectedExpTicket($expTicketId, $data);
            }

        } catch (EwhExportException $ex) {
            $result['error']['code'] = $ex->getErrorCode();
            $result['error']['mess'] = EwhErrorCode::getErrorMess($ex->getErrorCode());
            $this->logger->error('actionCreateExportTicketAjax fail. Error detail: '. $ex->getMessage());
        } catch (Exception $ex) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error('actionCreateExportTicketAjax fail. Error detail: '. $ex->getMessage());

        }
         
        $this->logger->info('Finish actionCreateExportTicketAjax');
        return json_encode($result);
    }


}
?>